<template>
  <div>
    <div class="gva-search-box">
      <el-form :inline="true" :model="searchInfo" class="demo-form-inline">
        <el-form-item label="奖品类型">
          <el-select v-model="searchInfo.type" placeholder="搜索条件" style="width: 100%" clearable>
            <el-option v-for="(item, key) in typeOptions" :key="key" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button size="mini" type="primary" icon="search" @click="onSubmit">查询</el-button>
          <el-button size="mini" icon="refresh" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button size="mini" type="primary" icon="plus" @click="openDialog">新增</el-button>
        <!-- <el-popover v-model:visible="deleteVisible" placement="top" width="160">
          <p>确定要删除吗？</p>
          <div style="text-align: right; margin-top: 8px">
            <el-button size="mini" type="text" @click="deleteVisible = false">取消</el-button>
            <el-button size="mini" type="primary" @click="onDelete">确定</el-button>
          </div>
          <template #reference>
            <el-button icon="delete" size="mini" style="margin-left: 10px" :disabled="!multipleSelection.length">删除</el-button>
          </template>
        </el-popover> -->
      </div>
      <el-table ref="multipleTable" style="width: 100%" tooltip-effect="dark" :data="tableData" row-key="ID" @selection-change="handleSelectionChange">
        <el-table-column align="center" label="奖品id" prop="ID" />
        <el-table-column align="center" label="奖品名称" prop="goodsName" />
        <el-table-column align="center" label="备注" prop="remark" />
        <el-table-column align="center" label="图片地址" prop="goodsUrl">
          <template #default="scope">
            <el-image style="width: 40px" fit="scale-down" :src="scope.row.goodsUrl" :preview-src-list="[scope.row.goodsUrl]" :hide-on-click-modal="true" v-if="scope.row.goodsUrl" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="优惠券路径" prop="requestUrl" />
        <!-- <el-table-column align="center" label="优惠券appId" prop="appId" /> -->
        <el-table-column align="center" label="奶滴数" prop="needNum" />
        <el-table-column align="center" label="库存数量" prop="inventoryNum" />
        <el-table-column align="center" label="概率" prop="probability" />
        <el-table-column align="center" label="已领取数量" prop="haveNum" />
        <!-- <el-table-column align="center" label="奖品类型" prop="goodsType" /> -->
        <el-table-column align="center" label="奖品类型" prop="type">
          <template #default="scope">
            {{ filterDict(scope.row.type, "type") }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="是否启用" prop="isDelete">
          <template #default="scope">
            <el-tag class="ml-2" :type="!scope.row.isDelete ? '' : 'danger'">{{ !scope.row.isDelete ? "是" : "否" }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="排序" prop="sour" />
        <el-table-column align="center" label="创建日期">
          <template #default="scope">{{ formatDate(scope.row.CreatedAt) }}</template>
        </el-table-column>
        <el-table-column align="center" label="按钮组">
          <template #default="scope">
            <el-button type="text" icon="edit" size="small" class="table-button" @click="updateGoodsInfo(scope.row)">变更</el-button>
            <el-button type="text" icon="delete" size="mini" @click="deleteRow(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="page"
          :page-size="pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
    <el-dialog v-model="dialogFormVisible" :before-close="closeDialog" title="弹窗操作" width="580px">
      <el-form :model="formData" label-position="right" label-width="80px">
        <el-form-item label="奖品名称:">
          <el-input v-model="formData.goodsName" clearable placeholder="请输入" />
        </el-form-item>
        <el-form-item label="备注:">
          <el-input v-model="formData.remark" clearable placeholder="请输入" />
        </el-form-item>
        <!-- <el-form-item label="备注:">
          <el-input v-model="formData.remark" clearable placeholder="请输入" />
        </el-form-item> -->
        <el-form-item label="奖品类型:">
          <el-select v-model="formData.type" placeholder="请选择" style="width: 100%" clearable>
            <el-option v-for="(item, key) in typeOptions" :key="key" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="奶滴数:" v-if="formData.type === 1">
          <el-input v-model.number="formData.needNum" clearable placeholder="请输入" />
        </el-form-item>
        <!-- <el-form-item label="appid:" v-if="formData.type === 2">
          <el-input v-model="formData.appId" clearable placeholder="请输入" />
        </el-form-item> -->
        <el-form-item label="领取路径:" v-if="formData.type === 2">
          <el-input v-model="formData.requestUrl" clearable placeholder="请输入" />
        </el-form-item>
        <el-form-item label="库存数量:">
          <el-input v-model.number="formData.inventoryNum" clearable placeholder="请输入" />
        </el-form-item>
        <el-form-item label="概率:">
          <el-input v-model.number="formData.probability" clearable placeholder="请输入" />
        </el-form-item>
        <el-form-item label="排序:">
          <el-input v-model.number="formData.sour" clearable placeholder="请输入" />
        </el-form-item>
        <el-form-item label="是否启用:">
          <el-switch v-model="formData.isDelete" :active-value="0" :inactive-value="1" />
        </el-form-item>
        <el-form-item label="图片地址:">
          <el-upload
            :action="`${path}/fileUploadAndDownload/upload`"
            :before-upload="checkFile"
            :headers="{ 'x-token': token }"
            :on-error="uploadError"
            :on-success="uploadSuccess"
            :show-file-list="false"
            accept="image/png, image/jpeg"
          >
            <div class="el-upload el-upload--picture-card" v-if="!formData.goodsUrl">
              <el-icon><plus /></el-icon>
            </div>
            <el-image v-else style="width: 148px; height: 148px" fit="scale-down" :src="formData.goodsUrl" />
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" @click="closeDialog">取 消</el-button>
          <el-button size="small" type="primary" @click="enterDialog">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
const path = import.meta.env.VITE_BASE_API
import { mapGetters } from "vuex"
import { createGoodsInfo, deleteGoodsInfo, deleteGoodsInfoByIds, updateGoodsInfo, findGoodsInfo, getGoodsInfoList } from "@/api/goodsInfo" //  此处请自行替换地址
import infoList from "@/mixins/infoList"
const _formData = {
  needNum: 0,
  haveNum: 0,
  goodsName: "",
  goodsType: 2,
  inventoryNum: 0,
  type: 3,
  goodsUrl: "",
  sour: 0,
  createTime: new Date(),
  updateTime: new Date(),
  isDelete: 0,
  probability: 0,
  version: 0,
  appId: "",
  requestUrl: "",
}
export default {
  name: "GoodsInfo",
  mixins: [infoList],
  data() {
    return {
      listApi: getGoodsInfoList,
      dialogFormVisible: false,
      type: "",
      deleteVisible: false,
      multipleSelection: [],
      typeOptions: [],
      formData: { ..._formData },
      searchInfo: {
        goodsType: 2,
      },
      path,
    }
  },
  computed: {
    ...mapGetters("user", ["userInfo", "token"]),
  },
  async created() {
    await this.getTableData()
    await this.getDict("type")
  },
  methods: {
    onReset() {
      this.searchInfo = {
        goodsType: 2,
      }
    },
    checkFile(file) {
      this.fullscreenLoading = true
      const isJPG = file.type === "image/jpeg"
      const isPng = file.type === "image/png"
      const isLt2M = file.size / 1024 / 1024 < 0.5
      if (!isJPG && !isPng) {
        this.$message.error("上传图片只能是 jpg或png 格式!")
        this.fullscreenLoading = false
      }
      if (!isLt2M) {
        this.$message.error("图片大小不能超过 500KB")
        this.fullscreenLoading = false
      }
      return (isPng || isJPG) && isLt2M
    },
    uploadError() {
      this.$message({
        type: "error",
        message: "上传失败",
      })
      this.fullscreenLoading = false
    },
    uploadSuccess({ code, msg, data }) {
      this.fullscreenLoading = false
      if (code === 0) {
        this.$message({
          type: "success",
          message: "上传成功",
        })
        if (code === 0) {
          this.formData.goodsUrl = data.file.url
        }
      } else {
        this.$message({
          type: "warning",
          message: msg,
        })
      }
    },
    // 条件搜索前端看此方法
    onSubmit() {
      this.page = 1
      this.pageSize = 10
      this.getTableData()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    deleteRow(row) {
      this.$confirm("确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.deleteGoodsInfo(row)
      })
    },
    async onDelete() {
      const ids = []
      if (this.multipleSelection.length === 0) {
        this.$message({
          type: "warning",
          message: "请选择要删除的数据",
        })
        return
      }
      this.multipleSelection &&
        this.multipleSelection.map((item) => {
          ids.push(item.ID)
        })
      const res = await deleteGoodsInfoByIds({ ids })
      if (res.code === 0) {
        this.$message({
          type: "success",
          message: "删除成功",
        })
        if (this.tableData.length === ids.length && this.page > 1) {
          this.page--
        }
        this.deleteVisible = false
        this.getTableData()
      }
    },
    async updateGoodsInfo(row) {
      const res = await findGoodsInfo({ ID: row.ID })
      this.type = "update"
      if (res.code === 0) {
        this.formData = res.data.regoodsInfo
        this.dialogFormVisible = true
      }
    },
    closeDialog() {
      this.dialogFormVisible = false
      this.formData = {
        ..._formData,
      }
    },
    async deleteGoodsInfo(row) {
      const res = await deleteGoodsInfo({ ID: row.ID })
      if (res.code === 0) {
        this.$message({
          type: "success",
          message: "删除成功",
        })
        if (this.tableData.length === 1 && this.page > 1) {
          this.page--
        }
        this.getTableData()
      }
    },
    async enterDialog() {
      let res
      switch (this.type) {
        case "create":
          res = await createGoodsInfo(this.formData)
          break
        case "update":
          res = await updateGoodsInfo(this.formData)
          break
        default:
          res = await createGoodsInfo(this.formData)
          break
      }
      if (res.code === 0) {
        this.$message({
          type: "success",
          message: "创建/更改成功",
        })
        this.closeDialog()
        this.getTableData()
      }
    },
    openDialog() {
      this.type = "create"
      this.dialogFormVisible = true
    },
  },
}
</script>

<style></style>
